# @Time    : 2019/1/12 21:02
# @Author  : xufqing
from rest_framework.viewsets import ModelViewSet
from ..models import Menu
from ..serializers.menu_serializers import MenuSerializer
from apps.common.custom import CommonPagination,RbacPermission,TreeAPIView
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.response import Response


class MenuViewSet(ModelViewSet):
    '''
    角色管理：增删改查
    '''
    queryset = Menu.objects.all()
    serializer_class = MenuSerializer
    pagination_class = CommonPagination
    filter_backends = (SearchFilter, OrderingFilter)
    search_fields = ('name',)
    ordering_fields = ('sort',)
    authentication_classes = (JSONWebTokenAuthentication,)
    permission_classes = (RbacPermission,)

    def list(self, request, *args, **kwargs):
        #重写list方法，获取树状结构数据
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            tree_dict = {}
            tree_data = []
            try:
                for item in serializer.data:
                    tree_dict[item['id']] = item
                for i in tree_dict:
                    tree_dict[i]['children'] = []
                    if tree_dict[i]['pid']:
                        pid = tree_dict[i]['pid']
                        parent = tree_dict[pid]
                        parent['children'].append(tree_dict[i])
                    else:
                        tree_data.append(tree_dict[i])
                return self.get_paginated_response(tree_data)
            except KeyError:
                return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class MenuTreeView(TreeAPIView):
    '''
    菜单树
    '''
    queryset = Menu.objects.all()
